package com.fcfactory.eggutils.documentUtil;

import cn.hutool.core.io.FileUtil;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @autuor 范大晨
 * @Date 2023/9/19 19:56
 * @description properties格式配置文件转Yml格式
 */
public class Properties2YmlUtil {
    /**
     * properties转yml
     * @param propertiesPath 本地properties文件路径
     * @param propertiesCharset properties文件编码
     * @param ymlCharset yml文件编码
     */
    public static void propertiesToYml(String propertiesPath,String propertiesCharset,String ymlCharset){
        List<String> lines = FileUtil.readLines(propertiesPath, propertiesCharset);
        String path = FileUtil.getAbsolutePath(propertiesPath);
        //使用treemap排好序
        Map<String,String> sourceMap = new TreeMap<String,String>();
        for (String line:lines){
            if (!StringUtils.isEmpty(line) && !line.startsWith("#")){
                String key = line.substring(0,line.indexOf("="));
                String value = line.substring(line.indexOf("=")+1);
                sourceMap.put(key,value);
            }
        }
        Iterator<String> it = sourceMap.keySet().iterator();
        //保存yml的行内容
        List<String> ymlLines = new ArrayList<String>();
        //Tab用两个空格格式化
        String tab = "  ";
        //yml文档树
        Map<String,List<String>> treeMap = new TreeMap<String,List<String>>();
        //父级名称
        String parent = "";
        //子节点列表
        List<String> element = new ArrayList<String>();

        while(it.hasNext()){
            String key = it.next();
            //.拆分key
            String[] keys = key.split("\\.");
            String prefix = "";
            for (int i=0;i<keys.length;i++){
                //从第二个节点开始，行前面需要加tab来格式化，并设置它的父节点
                if (i>0){
                    parent+=keys[i-1];
                    prefix += tab;
                }
                String line = prefix + keys[i]+ ": ";
                treeMap.computeIfAbsent(parent, k -> new ArrayList<String>());
                if(!treeMap.get(parent).contains(line)){
                    element = treeMap.get(parent)==null?new ArrayList<String>():treeMap.get(parent);
                    if (!element.contains(line)){
                        element.add(line);
                        treeMap.put(parent,element);
                    }
                    if (i==keys.length-1){
                        ymlLines.add(line+sourceMap.get(key));
                        parent = "";
                    }else{
                        ymlLines.add(line);
                    }
                }
            }
        }
        FileUtil.writeLines(ymlLines,path.replace(".properties",".yml"),ymlCharset);
    }
}
